package cn.player.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.ViewGroup;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;

import cn.player.R;


/**
 * Created by DD_ZGL on 2016/3/29.
 */
public class SlidingMenuView extends HorizontalScrollView {

    private LinearLayout mWrapper;
    private ViewGroup mMenuWrapper;
    private ViewGroup mContentWrapper;
    private int mScreenWidth;
    private int mMenuWidth;
    private int mMenuDefaultRightPadding;
    private int mMenuRightPadding;

    private int mMenuCanSlideDefaultPadding;
    private int mMenuCanSlidePadding;


    /**判断onMeasure只执行一次*/
    private boolean once;
    /**判断menu是否打开*/
    private boolean mIsMenuOpen;

    private int mStartX;

    /**
     * 只在new SlidingMenuView(context)时调用
     *
     * @param context
     */
    public SlidingMenuView(Context context) {
        super(context);
        Log.i("zl", "SlidingMenuView()");
    }

    /**
     * 布局文件中声明，使用自定义属性也会调用
     * 注意：此方法在super中调用的还是包含三个参数的构造方法，并传默认的对应控件style
     * this(context, attrs, com.android.internal.R.attr.horizontalScrollViewStyle);
     *
     * @param context
     * @param attrs
     */
    public SlidingMenuView(Context context, AttributeSet attrs) {
        super(context, attrs);
        Log.i("zl", "SlidingMenuView(context,attrs)");
        initDefaultAttribute(context,attrs);
    }

    public SlidingMenuView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initDefaultAttribute(context,attrs);

    }

    private void initDefaultAttribute(Context context, AttributeSet attrs){
        mScreenWidth = getContext().getResources().getDisplayMetrics().widthPixels;
        mMenuDefaultRightPadding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, mScreenWidth/4, context.getResources().getDisplayMetrics());
        mMenuCanSlideDefaultPadding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, mScreenWidth, context.getResources().getDisplayMetrics());
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.SlidingMenu);
        mMenuRightPadding = typedArray.getDimensionPixelOffset(R.styleable.SlidingMenu_rightPadding, mMenuDefaultRightPadding);
        mMenuCanSlidePadding = typedArray.getDimensionPixelOffset(R.styleable.SlidingMenu_canSlidePadding, mMenuCanSlideDefaultPadding);

        typedArray.recycle();

        Log.i("zl", "mMenuDefaultRightPadding = " + mMenuDefaultRightPadding + ",mMenuRightPadding = " + mMenuRightPadding);
    }



    /**
     * 计算子View的宽和高，以及设置自己的宽和高
     * 注意：onMeasure有可能被多次调用
     *
     * @param widthMeasureSpec
     * @param heightMeasureSpec
     */
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        if (!once) {
            Log.i("zl", "onMeasure(),widthMeasureSpec = " + widthMeasureSpec + ",heightMeasureSpec = " + heightMeasureSpec);
            once = true;
            mMenuWidth = mScreenWidth - mMenuRightPadding;
            mWrapper = (LinearLayout) getChildAt(0);
            mMenuWrapper = (ViewGroup) mWrapper.getChildAt(0);
            mContentWrapper = (ViewGroup) mWrapper.getChildAt(1);
            mMenuWrapper.getLayoutParams().width = mMenuWidth;
            mContentWrapper.getLayoutParams().width = mScreenWidth;
        }

    }

    /**
     * ViewGroup决定子View的布局的位置
     *
     * @param changed
     * @param l
     * @param t
     * @param r
     * @param b
     */
    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        Log.i("zl", "onLayout(),changed = " + changed);
        Log.i("zl", "onLayout(),l = " + l + ",t = " + t + ",r = " + r + ",b = " + b);
        if (changed) {
            scrollTo(mMenuWidth, 0);
        }
    }

    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        super.onScrollChanged(l, t, oldl, oldt);
//        Log.i("zl", "onScrollChanged(),l = " + l + ",oldl = " + oldl + ",oldt = " + oldt);
        float scale = l * 1.0f / mMenuWidth; //l-(mMenuWidth~0)，scale-(1~0)

        float menuAlpha = 0.6f + 0.4f * (1 - scale);//0.6~1.0
        mMenuWrapper.setAlpha(menuAlpha);

//        mMenuWrapper.setTranslationX(l);//模拟menu菜单被content覆盖的效果
        mMenuWrapper.setTranslationX(l * 0.6f);

        float menuScale = 1.0f - scale * 0.3f;//0.7~1.0
        mMenuWrapper.setScaleX(menuScale);
        mMenuWrapper.setScaleY(menuScale);

        float contentScale = 0.7f + 0.3f * scale;//1.0~0.7
        mContentWrapper.setPivotX(0);
        mContentWrapper.setPivotY(mContentWrapper.getHeight() / 2);
        mContentWrapper.setScaleX(contentScale);
        mContentWrapper.setScaleY(contentScale);

    }

    /**
     * 自定义View的内容,考虑绘制内容区域即可
     *
     * @param canvas
     */
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
//        Log.i("zl", "onDraw()");
    }

    /**
     * 事件拦截方法,
     *
     * @param ev
     * @return
     *      返回true，则将事件拦截，交出自己的onTouchEvent处理
     *      返回false，则将事件传给子view的onInterceptTouchEvent方法处理
     *
     */
    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mStartX = (int) ev.getX();
                Log.i("zl", "onInterceptTouchEvent() ACTION_DOWN mStartX = " + mStartX);
                break;
            case MotionEvent.ACTION_MOVE:
//                Log.i("zl", "onInterceptTouchEvent() ACTION_MOVE");
                break;
            case MotionEvent.ACTION_UP:
                Log.i("zl", "onInterceptTouchEvent() ACTION_UP");
                break;
            case MotionEvent.ACTION_CANCEL:
                Log.i("zl", "onInterceptTouchEvent() ACTION_CANCEL");
                break;
        }

        if(!mIsMenuOpen && mStartX > mMenuCanSlidePadding){
            return false;
        }

        return super.onInterceptTouchEvent(ev);
    }

    /**
     * 事件分发方法
     *
     * @param ev
     * @return
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
//        Log.i("zl", "dispatchTouchEvent()");
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 监控用户的触摸事件
     *
     * @param ev
     * @return
     */
    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                Log.i("zl", "SlidingMenuView onTouchEvent() ACTION_DOWN");
                break;
            case MotionEvent.ACTION_MOVE:
                break;
            case MotionEvent.ACTION_UP:
                Log.i("zl", "SlidingMenuView onTouchEvent() ACTION_UP");
                int scrollX = getScrollX();
                if (scrollX >= mMenuWidth / 2) {
                    post(new Runnable() {
                        @Override
                        public void run() {
                            mIsMenuOpen = false;
                            smoothScrollTo(mMenuWidth, 0);
                        }
                    });
                } else {
                    post(new Runnable() {
                        @Override
                        public void run() {
                            mIsMenuOpen = true;
                            smoothScrollTo(0, 0);
                        }
                    });
                }
                break;
            case MotionEvent.ACTION_CANCEL:
                Log.i("zl", "onTouchEvent() ACTION_CANCEL");
                break;
        }
        return super.onTouchEvent(ev);
    }

    public void setMenuCanSlidePadding(int canSlidePadding){
        this.mMenuCanSlidePadding = canSlidePadding;
    }


    /**
     * 打开侧滑菜单
     */
    public void openMenu(){
        if(mIsMenuOpen){
            return;
        }
        post(new Runnable() {
            @Override
            public void run() {
                mIsMenuOpen = true;
                smoothScrollTo(0, 0);
            }
        });
    }

    /**
     * 关闭侧滑菜单
     */
    public void closeMenu(){
        if(!mIsMenuOpen){
            return;
        }
        post(new Runnable() {
            @Override
            public void run() {
                mIsMenuOpen = false;
                smoothScrollTo(mMenuWidth, 0);
            }
        });
    }

    /**
     * 关闭/打开侧滑菜单
     */
    public void toggleMenu(){
        if(mIsMenuOpen){
            closeMenu();
        }else{
            openMenu();
        }
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        return super.dispatchKeyEvent(event);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return super.onKeyDown(keyCode, event);
    }



    @Override
    public void computeScroll() {
        super.computeScroll();
    }

    @Override
    protected int computeScrollDeltaToGetChildRectOnScreen(Rect rect) {
//        return super.computeScrollDeltaToGetChildRectOnScreen(rect);
        return 0;//返回0可防止子view滚动时当前scrollview也跟随滑动
    }

}
